<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="90px"
    >
      <el-form-item label="名称" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb-8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['saas:ad:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['saas:ad:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:ad:remove']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="adList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column
        label="名称"
        align="center"
        prop="title"
        min-width="120"
      />
      <el-table-column
        label="广告位名称"
        align="center"
        prop="region"
        min-width="120"
      >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ad_region" :value="scope.row.region" />
        </template>
      </el-table-column>
      <el-table-column
        label="地址"
        align="center"
        prop="linkUrl"
        min-width="200"
      />
      <el-table-column label="图片地址" align="center" prop="img" width="100">
        <template slot-scope="scope">
          <image-preview v-if="scope.row.img" :src="scope.row.img" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="文本" align="center" prop="text" min-width="300" show-overflow-tooltip />
      <el-table-column label="小程序id" align="center" prop="appid" width="150" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="120px"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:ad:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:ad:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改资源对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="广告位" prop="region">
          <el-select v-model="form.region" placeholder="广告位">
            <el-option
              v-for="dict in dict.type.ad_region"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="单位" prop="appid">
          <el-select
            v-model="form.jigouId"
            v-loadMore="selectLoadMore"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in selectList"
              :key="item.id"
              :label="item.cname"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="地址" prop="linkUrl">
          <el-input v-model="form.linkUrl" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="图片地址">
          <ImageUpload  v-model="form.img" />
        </el-form-item>
        <el-form-item label="文本" prop="text">
          <el-input v-model="form.text" placeholder="请输入文本" />
        </el-form-item>
        <el-form-item label="小程序id" prop="appid">
          <el-input v-model="form.appid" placeholder="请输入小程序id" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAd, getAd, delAd, addAd, updateAd } from "@/api/saas/ad";
import { listCompany } from "@/api/company/company";
import ImageUpload from '@/components/ImageUpload'

export default {
  name: "Ad",
  dicts: ["ad_region"],
  components: {
    ImageUpload
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 资源表格数据
      adList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" },
        ],
      },

      selectList: [],
      selectTotal: 0,
      selectParams: {
        finish: false, // 是否加载完毕
        pageNum: 1,
        pageSize: 999,
        jigouId: "", // 机构回显ID
      },
    };
  },
  created() {
    this.getList();
  },
  activated() {
    this.getList();
  },
  methods: {
    /** 查询资源列表 */
    getList() {
      this.loading = true;
      listAd(this.queryParams).then((response) => {
        this.adList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        region: null,
        linkUrl: null,
        img: null,
        text: null,
        appid: null,
        createTime: null,
        updateTime: null,
      };
      this.selectList = [];
      Object.assign(this.$data.selectParams, this.$options.data().selectParams);
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    async handleAdd() {
      this.reset();
      await this.getSelectList();
      this.open = true;
      this.title = "添加资源";
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      const response = await getAd(id);
      this.form = response.data;
      this.selectParams.jigouId = response.data.jigouId;
      await this.getSelectList();

      this.open = true;
      this.title = "修改资源";
    },

    // 获取机构列表
    async getSelectList() {
      if (this.selectParams.finish) return;

      const response = await listCompany(this.selectParams);
      this.selectList = [...this.selectList, ...response.rows];
      this.selectParams.finish = this.selectList.length == response.total; // 已加载完毕
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateAd(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAd(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除资源编号为"' + ids + '"的数据项？')
        .then(function () {
          return delAd(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    selectLoadMore() {
      this.selectParams.pageNum = this.selectParams.pageNum++;
      this.getSelectList();
    },
  },
};
</script>
